package win.ganbo.easyframwork.commons.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import win.ganbo.easyframwork.commons.shiro.ShiroUser;
import win.ganbo.easyframwork.domain.Permission;
import win.ganbo.easyframwork.domain.User;
import win.ganbo.easyframwork.service.IPermissionService;
import win.ganbo.easyframwork.service.IRoleService;
import win.ganbo.easyframwork.service.IUserService;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CustomDBReam extends AuthorizingRealm{

	@Autowired
	private IUserService userService;
	@Autowired
	private IRoleService roleService;
	@Autowired
	private IPermissionService permissionService;

	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		
		String username = token.getPrincipal().toString();

		System.out.println("登陆Shiro realm=====认证====>"+username);

		List<Object> params = new ArrayList<>();
		params.add(username);
		List<User> users = userService.findByHql("select o from User o where o.username = ?1 ", params);


		System.out.println("users=====>"+users);
		//数据库中没有查到登陆用户就返回null
		if(users==null || users.size()!=1){
			return null;
		}
		
		User user = users.get(0);
		ShiroUser shiroUser = new ShiroUser();
		shiroUser.setUsername(user.getUsername());
		System.out.println("登陆成功....."+user);

		String salt = user.getSalt(); //加盐
		SimpleAuthenticationInfo userInfo= new SimpleAuthenticationInfo(shiroUser,user.getPassword(), ByteSource.Util.bytes(salt),getName());
		return userInfo;
	}
	
	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ShiroUser  primaryPrincipal = (ShiroUser) principals.getPrimaryPrincipal();


		System.out.println("权限检查。。。。。。。。。。。。。。。。。。");
		//从数据库查询当前登陆用户的权限信息
		Set<Permission> permissions = new HashSet<Permission>();
		Set<String> permissionStrs = new HashSet<>();
		
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

		//将上面查到的权限的信息添加到authorizationInfo中
		authorizationInfo.setStringPermissions(permissionStrs);
		return authorizationInfo;
	}



}
